<!-- pages/wallet/withdraw.vue -->
<template>
  <view class="page-container">
    <!-- 提现表单 -->
    <scroll-view scroll-y class="form-container">
      <view class="form-card">
        <view class="form-item">
          <text class="form-label">账户余额（元）</text>
          <text class="form-value">{{ balance.toFixed(2) }}</text>
        </view>

        <view class="form-item">
          <text class="form-label">提现金额</text>
          <input 
            v-model="form.amount"
            type="number"
            placeholder="请输入提现金额"
            class="form-input"
            :class="{ error: formErrors.amount }"
          />
          <text class="form-tip">最小提现金额100元</text>
        </view>

        <view class="form-item">
          <text class="form-label">真实姓名</text>
          <input 
            v-model="form.realName"
            placeholder="请输入真实姓名"
            class="form-input"
            :class="{ error: formErrors.realName }"
          />
        </view>

        <view class="form-item">
          <text class="form-label">开户银行</text>
          <picker 
            :range="bankList" 
            range-key="name"
            @change="handleBankChange"
          >
            <view class="picker">
              {{ selectedBank.name || '请选择银行' }}
              <uni-icons type="arrowright" size="16" color="#999" />
            </view>
          </picker>
        </view>

        <view class="form-item">
          <text class="form-label">银行卡号</text>
          <input 
            v-model="form.cardNumber"
            type="number"
            placeholder="请输入银行卡号"
            class="form-input"
            :class="{ error: formErrors.cardNumber }"
          />
        </view>

        <button 
          class="submit-btn"
          :class="{ disabled: !formValid }"
          @tap="handleSubmit"
        >
          确认信息并提现
        </button>
      </view>

      <!-- 提现记录 -->
      <view class="record-section">
        <view class="section-header">
          <text class="section-title">提现记录</text>
          <uni-icons 
            type="refreshempty" 
            size="18" 
            color="#666" 
            @tap="loadRecords"
          />
        </view>

        <view 
          v-for="(record, index) in records" 
          :key="index"
          class="record-card"
        >
          <view class="card-left">
            <text class="bank-name">{{ getBankName(record.bankCardType) }}</text>
            <text class="record-time">{{ formatDate(record.createTime) }}</text>
          </view>
          <view class="card-right">
            <text :class="['amount', statusClassMap[record.auditStatus]]">
              -{{ record.amount.toFixed(2) }}
            </text>
            <view :class="['status', statusClassMap[record.auditStatus]]">
              {{ statusDict[record.auditStatus] }}
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 加载状态 -->
    <uni-load-more :status="loadingStatus" />
  </view>
  
  <view v-if="showSuccessModal" class="success-modal">
    <view class="modal-content">
      <view class="success-icon">
        <uni-icons type="checkmarkempty" size="60" color="#fff" />
      </view>
      <text class="success-text">提交成功</text>
      <text class="success-tip">等待平台审核</text>
      <button 
        class="confirm-btn"
        @tap="handleBackHome"
      >
        返回首页
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import request from '../../utils/request'

// 工具函数
const formatDate = timestamp => {
  const date = new Date(timestamp)
  return `${date.toLocaleDateString()} ${date.getHours().toString().padStart(2,'0')}:${date.getMinutes().toString().padStart(2,'0')}`
}

// 响应式状态
const balance = ref(0)
const form = reactive({
  amount: '',
  realName: '',
  bankCode: '',
  cardNumber: ''
})
const formErrors = reactive({
  amount: false,
  realName: false,
  cardNumber: false
})
const selectedBank = ref({ code: null, name: '' })
const records = ref([])
const loadingStatus = ref('more')
const showSuccessModal = ref(false)

// 静态数据
const bankList = ref([])
const statusDict = ref({})
const statusClassMap = {
  '1': 'status-pending',   // 对应未审核
  '2': 'status-success',   // 对应已通过
  '3': 'status-failed'     // 对应已拒绝
}

const loadDictData = async () => {
  try {
    const [bankRes, statusRes] = await Promise.all([
      request({ url: '/system/dict/data/type/bank_card_type' }),
      request({ url: '/system/dict/data/type/store_status' })
    ])

    // 处理银行数据
    if (bankRes.code === 200) {
        bankList.value = bankRes.data.map(item => ({
        name: item.dictLabel,
        code: parseInt(item.dictValue) 
        }))
    }

    // 处理状态数据
    if (statusRes.code === 200) {
        statusDict.value = statusRes.data.reduce((acc, cur) => {
        acc[cur.dictValue] = cur.dictLabel
        return acc
        }, {})
        }
  } catch (error) {
    console.error('字典加载失败:', error)
  }
}

// 计算属性
const formValid = computed(() => {
  return form.amount >= 100 && 
         form.realName.length >= 2 &&
         selectedBank.code &&
         /^\d{16,19}$/.test(form.cardNumber)
})

const getBankName = (type) => {
  return bankList.value.find(item => item.code === type)?.name || '未知银行'
}

// 生命周期
onLoad((options) => {
  // 接收前页传递的余额
  if (options.balance) {
    balance.value = parseFloat(options.balance)
  }
  loadDictData()
  loadRecords()
})

// 数据加载
const loadBalance = async () => {
  // 模拟接口请求
  setTimeout(() => {
    balance.value = 8520.50
  }, 500)
}

const loadRecords = async () => {
  try {
      const res = await request({ url: '/serviceItem/withdrawalRecord/list' })
      if (res.code === 200) {
        records.value = res.data.map(item => ({
          ...item,
          createTime: item.withdrawalTime
        }))
      }
    } catch (error) {
    uni.showToast({ title: '记录加载失败', icon: 'none' })
  } finally {
    loadingStatus.value = 'noMore'
  }
}

// 事件处理
const handleBankChange = (e) => {
  const selected = bankList.value[e.detail.value]
  form.bankCode = selected.code        // 保持数字类型
  selectedBank.value = {               // 使用响应式对象
    name: selected.name,
    code: selected.code
  }
  console.log('当前选择的银行:', selected) // 调试日志
}

const validateForm = () => {
  formErrors.amount = form.amount < 100 || form.amount > balance.value
  formErrors.realName = form.realName.length < 2
  formErrors.cardNumber = !/^\d{16,19}$/.test(form.cardNumber)
  return !Object.values(formErrors).some(Boolean)
}

const handleSubmit = async () => {
  if (!validateForm()) return
  
  uni.showLoading({ title: '提交中...', mask: true })
  
  try {
    // 构造符合接口规范的请求数据
    const requestData = {
      amount: parseFloat(form.amount),    // 转换为数字类型
      ext1: form.realName,                // 真实姓名存储到ext1字段
      bankCardType: selectedBank.value.code,    // 使用字典值对应的编码
      bankCardNo: form.cardNumber,        // 保持字段名称一致
    }

    const res = await request({
      url: '/serviceItem/withdrawalRecord/apply',
      method: 'post',
      data: requestData
    })

    if (res.code === 200) {
      // 成功处理
      showSuccessModal.value = true
      // 刷新记录列表
      await loadRecords()
      // 更新本地余额（实际应重新获取接口数据）
      balance.value = (balance.value - form.amount).toFixed(2)
      // 清空表单
      form.amount = ''
      form.realName = ''
      form.cardNumber = ''
      selectedBank.name = ''
    } else {
      // 处理业务逻辑错误
      const errorMap = {
        1001: '余额不足',
        1002: '银行卡信息有误',
        1003: '审核中的提现记录已达上限'
      }
      uni.showToast({
        title: errorMap[res.code] || res.msg || '提现申请失败',
        icon: 'none'
      })
    }
  } catch (error) {
    // 网络异常处理
    uni.showToast({ 
      title: error.errMsg || '网络连接异常',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

const handleBackHome = () => {
  showSuccessModal.value = false
  uni.reLaunch({
    url: '/pages/index'
  })
}
</script>

<style lang="scss" scoped>
.page-container {
  background: #f8f9fa;
  min-height: 100vh;
}

.form-container {
  padding: 24rpx;
  height: calc(100vh - var(--window-top));
}

.form-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
}

.form-item {
  margin-bottom: 40rpx;
  
  .form-label {
    display: block;
    font-size: 28rpx;
    color: #666;
    margin-bottom: 16rpx;
  }
  
  .form-value {
    font-size: 36rpx;
    color: #e4393c;
    font-weight: 600;
  }
  
  .form-input {
    height: 80rpx;
    padding: 0 20rpx;
    background: #f5f5f5;
    border-radius: 8rpx;
    font-size: 28rpx;
    
    &.error {
      border: 1rpx solid #e4393c;
    }
  }
  
  .form-tip {
    font-size: 24rpx;
    color: #999;
    margin-top: 8rpx;
  }
}

.picker {
  height: 80rpx;
  padding: 0 20rpx;
  background: #f5f5f5;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.submit-btn {
  margin-top: 48rpx;
  height: 88rpx;
  line-height: 88rpx;
  background: linear-gradient(135deg, #1890ff, #096dd9);
  color: #fff;
  border-radius: 44rpx;
  font-size: 32rpx;
  
  &.disabled {
    opacity: 0.6;
  }
}

.record-section {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24rpx;
    
    .section-title {
      font-size: 32rpx;
      color: #333;
      font-weight: 500;
    }
  }
}

.record-card {
  display: flex;
  justify-content: space-between;
  padding: 24rpx 0;
  border-bottom: 1rpx solid #eee;
  
  .card-left {
    flex: 1;
    
    .bank-name {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 12rpx;
	  margin-right: 10rpx;
    }
    
    .record-time {
      font-size: 24rpx;
      color: #999;
    }
  }
  
  .card-right {
    text-align: right;
    
    .amount {
      font-size: 32rpx;
      color: #e4393c;
      margin-bottom: 8rpx;
    }
    
    .status {
      font-size: 24rpx;
      padding: 4rpx 12rpx;
      border-radius: 8rpx;
      
      &-pending {
        color: #fa8c16;
        background: #fff7e6;
      }
      
      &-success {
        color: #52c41a;
        background: #f6ffed;
      }
      
      &-failed {
        color: #f5222d;
        background: #fff1f0;
      }
    }
  }
}
.success-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
  animation: modal-fade 0.3s ease;

  .modal-content {
    background: #fff;
    border-radius: 32rpx;
    padding: 48rpx;
    width: 80%;
    text-align: center;
  }

  .success-icon {
    width: 120rpx;
    height: 120rpx;
    background: #07c160;
    border-radius: 50%;
    margin: 0 auto 32rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    animation: scale-up 0.4s cubic-bezier(0.18, 0.89, 0.32, 1.28);
  }

  .success-text {
    display: block;
    font-size: 40rpx;
    color: #333;
    font-weight: 600;
    margin-bottom: 16rpx;
  }

  .success-tip {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 48rpx;
    display: block;
  }

  .confirm-btn {
    height: 88rpx;
    line-height: 88rpx;
    background: #07c160;
    color: #fff;
    border-radius: 44rpx;
    font-size: 32rpx;
    margin: 0 auto;
    width: 60%;
    
    &::after {
      border: none;
    }
  }
}

@keyframes modal-fade {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes scale-up {
  0% { transform: scale(0.5); opacity: 0; }
  90% { transform: scale(1.1); }
  100% { transform: scale(1); opacity: 1; }
}

.status-success .amount { color: #52c41a; }
.status-pending .amount { color: #fa8c16; }
.status-failed .amount { 
  color: #999;
  text-decoration: line-through;
}
</style>